package com.mooral.web.tag.html;

import java.util.ArrayList;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.struts.Globals;
import org.apache.struts.util.PropertyMessageResources;
import org.apache.struts.util.PropertyMessageResourcesFactory;

import com.mooral.context.Context;
import com.mooral.context.ContextSession;
import com.mooral.web.util.SlugUtils;


public class PaginationTag extends TagSupport {

	public static String LABEL_NEXT = "Next"; 
	public static String LABEL_PREVIOUS = "Previous"; 
	public static String LABEL_DOTS = "..."; 
	public static String LABEL_EMPTY = "EMPTY"; 
	
//    private String action;
    private int pageSize = Context.PAGE_SIZE;

    private int pageSelected;
    private int listSize;
    private String query = null;
    private String actionSearch;
    private String positionAnchor = "#bottom";
    
    
    
    public String getPositionAnchor() {
		return positionAnchor;
	}
    
	public void setPositionAnchor(String positionAnchor) {
		this.positionAnchor = positionAnchor;
	}
	

	public int doStartTag() {

    	
    	Locale locale = (Locale)((HttpServletRequest) pageContext.getRequest()).getSession().getAttribute(Globals.LOCALE_KEY);
    	
    	LABEL_NEXT = PropertyMessageResources.getMessageResources("MessageResources").getMessage(locale, "pagination.next.label");
    	LABEL_PREVIOUS = PropertyMessageResources.getMessageResources("MessageResources").getMessage(locale, "pagination.previous.label");
    	LABEL_EMPTY = PropertyMessageResources.getMessageResources("MessageResources").getMessage(locale, "pagination.empty.label");
    	
    	pageSelected 	= ((Integer) pageContext.getRequest().getAttribute("pageSelected")).intValue();
    	listSize 		= ((Integer) pageContext.getRequest().getAttribute("listSize")).intValue();
    	if(pageContext.getRequest().getAttribute("query")!=null)
    		query = pageContext.getRequest().getAttribute("query").toString();
    	actionSearch 	= pageContext.getRequest().getAttribute("actionSearch").toString();
    	
    	try {
    		
    	    if (listSize > 0) {
    			int y = ((listSize % pageSize == 0) ? (listSize / pageSize)
    				: ((listSize / pageSize) + 1));
    			int beginLinkNumeration = Math.max(1, (pageSelected / 10) * 10);
    			int endLinkNumeration = Math.min(beginLinkNumeration + 9, y);
    	
    			if ((listSize > pageSize) && (pageSelected > 1)) {
    			    // arma el link anterior
    			    this.getPrevious();
    			}
    	
    			if (listSize > pageSize) {
    			    // arma los links numericos
    			    this.getNumericLink(y, beginLinkNumeration, endLinkNumeration);
    			}
    	
    			if (pageSelected < y) {
    			    // arma el link siguiente
    			    this.getNext();
    			}

    	    } else {

    	    }
    	} catch (Exception e) {

    	    throw new RuntimeException(e);
    	}

    	return (SKIP_BODY);
        }

        public void getNext() throws Exception {
    		int page = pageSelected + 1;
    		this.getPaintingLink(LABEL_NEXT, page, "long_label");
        }

        public void getPrevious() throws Exception {
    		int page = pageSelected - 1;
    		this.getPaintingLink(LABEL_PREVIOUS, page, "long_label");
        }

    public void getNumericLink(int y, int beginLinkNumeration, int endLinkNumeration)
	    throws Exception {

		if (pageSelected > 9) { // TODO PARAMETRIZAR
		    // incluye "..." indicando que hay paginas anteriores a la pagina
		    // menor visible
		    getPaintingNoLink(LABEL_DOTS, "dots");
		}
		for (int i = beginLinkNumeration; i <= endLinkNumeration; i++) {
		    if (pageSelected != i) {
		    	this.getPaintingLink(String.valueOf(i), i, "label");
		    } else {
		    	this.getPaintingNoLink(String.valueOf(i), "current");
		    }
		}
	
		if ((endLinkNumeration + 1) < (listSize / pageSize)) {
		    // incluye "..." indicando que hay paginas posteriores a la pagina
		    // mayor visible
		    getPaintingNoLink(LABEL_DOTS, "dots");
		}
    }

    private void getPaintingLink(String link, Integer page, String extraClass) throws Exception {
    	
		JspWriter num = pageContext.getOut();
		
		num.print("<a class=\"" + extraClass + "\" href=/" + ContextSession.getCurrentContext().getApplicationName());
		if (query != null) {
			num.print((new SlugUtils()).getActionSlug(actionSearch, new String[]{query, page.toString()}));
		} else {
			// TODO 4Martin, volvi atras este cambio. En que afecta esto?
		    //num.print((new SlugUtils()).getActionSlug(actionSearch, new String[]{"", page.toString()}));
			num.print((new SlugUtils()).getActionSlug(actionSearch, new String[]{page.toString()}));
		}
		num.print(this.positionAnchor + ">" + link + "</a>");		
    }

    private void getPaintingNoLink(String link, String extraClass) throws Exception {
		JspWriter num = pageContext.getOut();
		num.print("<span class=\"" + extraClass + "\">" + link + "</span>");
    }


    public void getEmpty() throws Exception {
		JspWriter num = pageContext.getOut();
		num.print(LABEL_EMPTY);
    }

}